from pydantic import BaseModel, Field, field_validator, conint

from enums.protocol_type import ProtocolType


# 基础IP验证器（复用逻辑）
def validate_ip(ip: str) -> str:
    if ip.count('.') != 3:
        raise ValueError('IP地址格式不正确')
    for i in ip.split('.'):
        if not i.isdigit() or int(i) < 0 or int(i) > 255:
            raise ValueError('IP地址格式不正确')
    return ip


# 设备基础模型（复用公共字段）
class DeviceBase(BaseModel):
    device_name: str = Field(..., min_length=1, description="设备名称不能为空")
    ip: str = Field(..., description="IPv4地址")
    port: int = Field(..., ge=0, le=65535)  # 端口范围约束
    protocol: ProtocolType = Field(..., description="通讯类型枚举")

    # IP字段自定义验证
    @field_validator('ip')
    def check_ip_format(cls, v):
        return validate_ip(v)


# 创建设备模型
class CreateDevice(DeviceBase):
    pass  # 直接继承所有字段


# 编辑设备模型
class EditDevice(DeviceBase):
    device_id: int = Field(..., ge=0, description="设备ID必须为非负整数")


# 设备名称模型
class DeviceName(BaseModel):
    device_name: str = Field(..., min_length=1, description="设备名称不能为空")
